package org.jeecg.modules.deepseek.service;

import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.deepseek.ChatRequestBean;
import org.jeecg.modules.deepseek.pojo.ChatRequest;
import org.jeecg.modules.deepseek.pojo.ChatRequestExample;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class DeepSeekService {
    @Autowired
    private OpenAiChatModel deepseekChatModel;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    ChatRequestBean chatRequestBean;

    private static final long TIME_WINDOW = 60L;

    private static final int MAX_VISITS_PER_MINUTE = 10;

    public Map<String, String> functionCallingv1(String message,String ClientIp){
        Map<String, String> bodyMap = new HashMap<>();


        String redisKey = "chat:ip:" + ClientIp;

        Integer currentVisitCount = (Integer) redisUtil.get(redisKey);

        if (currentVisitCount != null && currentVisitCount >= MAX_VISITS_PER_MINUTE) {
            bodyMap.put("content","请联系我们的顾问老师，才能开通继续使用");
            return bodyMap;
        }

        final String[] body1 = new String[1];

        body1[0] = "系统出现BUG，请稍后再试";

        ChatRequest.Message system = new ChatRequest.Message("system", "你是公司内部的AI助手用户提问的内容，如果和函数无关，请不要调用函数，请格式化输出内容到html的<body>标签中");
        ChatRequest.Message user = new ChatRequest.Message("user", message);
        try {

            OpenAiApi.ChatCompletionRequest currentWeather =  chatRequestBean.createChatRequestFunction();


            List<OpenAiApi.FunctionTool> tools = currentWeather.tools();
            ResponseEntity<OpenAiApi.ChatCompletion> chatCompletionChunkResponseEntity = ChatRequestExample.requestDeepSeekChat(tools, List.of(system, user));

            Map<String, FunctionCallback> functionCallbackRegister = deepseekChatModel.getFunctionCallbackRegister();
            OpenAiApi.ChatCompletion body = chatCompletionChunkResponseEntity.getBody();
            if (body != null) {
                {
                    List<OpenAiApi.ChatCompletionMessage.ToolCall> toolCalls = body.choices().get(0).message().toolCalls();
                    if (toolCalls == null || toolCalls.isEmpty()) {
                        body1[0] = body.choices().get(0).message().content();
                        bodyMap.put("content", body1[0]);
                        return bodyMap;
                    }
                    body.choices().forEach(choice -> {
                        List<OpenAiApi.ChatCompletionMessage.ToolCall> toolCalls1 = choice.message().toolCalls();
                        Iterator<OpenAiApi.ChatCompletionMessage.ToolCall> iterator = toolCalls1.iterator();
                        while (iterator.hasNext()) {
                            OpenAiApi.ChatCompletionMessage.ToolCall toolCall = iterator.next(); // 获取当前元素
                            FunctionCallback functionCallback = functionCallbackRegister.get(toolCall.function().name());
                            String call = functionCallback.call(toolCall.function().arguments());
                            // 如果不是最后一个元素，继续迭代
                            if (iterator.hasNext()) {
                            } else {
                                bodyMap.put("content", call);
                                // 如果是最后一个元素，执行额外的逻辑
//                                ResponseEntity<OpenAiApi.ChatCompletion>
//                                        chatCompletionChunkResponseEntity1 = ChatRequestExample.requestDeepSeekChat(null, List.of(
//                                        system,
//                                        user,
//                                        new ChatRequest.Message("user", call)
//                                ));
//                                body1[0] = chatCompletionChunkResponseEntity1.getBody().choices().get(0).message().content();
//                                bodyMap.put("content", body1[0]);
                            }
                        }
                    });
                }
            }


            if (currentVisitCount == null) {
                redisUtil.set(redisKey, 1, TIME_WINDOW); // 第一次访问，设置过期时间
            } else {
                redisUtil.incr(redisKey, 1); // 增加访问次数
            }
            return bodyMap;


        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
